package com.nowcoder.community.controller;

import com.nowcoder.community.annotation.LoginRequired;
import com.nowcoder.community.entity.Event;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.event.EventProducer;
import com.nowcoder.community.service.LikeService;
import com.nowcoder.community.util.CommunityConstant;
import com.nowcoder.community.util.CommunityUtil;
import com.nowcoder.community.util.HostHolder;
import com.nowcoder.community.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@Controller
public class LikeController {

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private LikeService likeService;

    @Autowired
    private EventProducer eventProducer;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @RequestMapping(value = "/like", method = RequestMethod.POST)
    @ResponseBody
    @LoginRequired
    public String like(int entityType, int entityId, int entityUserId, int postId) {
        User loginUser = hostHolder.getUser();
        Map <String, Object> data = new HashMap<>();
        likeService.like(loginUser.getId(), entityType, entityId, entityUserId);

        // 当前登录用户对帖子或评论的点赞状态
        boolean likeStatus = likeService.getEntityLikeStatus(loginUser.getId(), entityType, entityId);
        data.put("likeStatus", likeStatus);

        // 当前帖子或评论的点赞数
        data.put("likeCount", likeService.getEntityLikeCount(entityType, entityId));

        // 触发点赞主题的系统通知事件（当点赞的目标对象不是当前登录用户才触发）
        if (likeStatus && loginUser.getId() != entityUserId) {
            Event event = new Event()
                    .setTopic(CommunityConstant.TOPIC_LIKE)
                    .setUserId(loginUser.getId())
                    .setEntityType(entityType)
                    .setEntityId(entityId)
                    .setEntityUserId(entityUserId)
                    .setData("postId", postId);
            eventProducer.produceEvent(event);
        }

        if (entityType == CommunityConstant.ENTITY_TYPE_POST) {
            // 将postId存入redis，用于定时任务更新帖子score
            String postScoreKey = RedisKeyUtil.getPostScoreKey();
            redisTemplate.opsForSet().add(postScoreKey, postId);
        }

        return CommunityUtil.getJSONString(0, null, data);
    }

}
